import { IFeidaoAiBrowserComponent } from '@dfeidao/atom-web/interfaces';
import get from '@dfeidao/atom-web/local/get';
import nodejs from '@dfeidao/atom-web/msg/nodejs';
import error from '@dfeidao/atom-web/msgbox/error';
import { spaceid } from '../../atom/config';
export default async function a009(fd: IFeidaoAiBrowserComponent, args: {}) {
	// 拖动
	const ev = args as DragEvent;
	ev.preventDefault();
	const aim_node = ev.currentTarget as HTMLDivElement;// 放置目标节点
	const level_no = get(fd, 'level_no22');
	const draged_node = fd.data.node.querySelector<HTMLElement>(`[level_no="${level_no}"]`);// 被拖动节点
	const list = aim_node.parentElement as HTMLDivElement;// 父节点
	list.insertBefore(draged_node, aim_node);// 插队
	const aim_p = Number(aim_node.getAttribute('order_num'));
	const draged_p = Number(draged_node.getAttribute('order_num'));
	const min = Math.min(aim_p, draged_p);
	const max = Math.max(aim_p, draged_p);
	const items = Array.from(list.querySelectorAll<HTMLDivElement>('[draggable="true"]'));
	const edititems = items.filter((it) => {
		const order_num = Number(it.getAttribute('order_num'));
		return order_num >= min && order_num <= max;
	}).reverse();
	// 所有要重新排序的节点;
	const asc = get(fd, 'asc') as [] || '';
	const desc = get(fd, 'desc') as [];
	if (asc.length > 0 || !asc) {
		edititems.reduceRight((p, node) => {
			node.setAttribute('order_num', p.toString());
			return ++p;
		}, min);
	} else if (desc.length > 0) {
		edititems.reduce((p, node) => {
			node.setAttribute('order_num', p.toString());
			return ++p;
		}, min);
	}
	// 排序持久化操作
	const x = aim_node.getAttribute('level_no');
	const updsort1 = { level_no, order_num: aim_p };
	const updsort2 = { level_no: x, order_num: draged_p };
	if (level_no !== x) {
		const res1 = await nodejs('level-inf/zj-000001/s010', { productid: spaceid, updsort1, updsort2 });
		if (res1 === 'fail') {
			error("排序失败");
		}
	}
}
